package com.foo.DAO;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.foo.Entity.HistoricalData;

public class SnapshotDAOImpl implements SnapshotTemporalDAO
{
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    MapSqlParameterSource namedParameters =null;
    String query = "";
	 HistoricalData[] ticker =null;
	 int size=0;
	 
    public void setDataSource(DataSource dataSource) {
	    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	@Override
	public HistoricalData[] selectForum(String sorttype,Date fromdate, Date todate) 
	{
		try
		{
		 query = "select * from historicalstockdata where ticker_symbol = :ticker_symbol and deals_date between :fromdate and :todate";
		 namedParameters = new MapSqlParameterSource();
		 namedParameters.addValue("ticker_symbol", sorttype);
		 namedParameters.addValue("fromdate", fromdate);
		 namedParameters.addValue("todate", todate);
	
		
		return (HistoricalData[]) namedParameterJdbcTemplate.queryForObject(query,
				namedParameters, new RowMapper() {
			public Object mapRow(ResultSet resultSet, int rowNum)
					throws SQLException {
					int j=0;
					if (resultSet !=null)
					{
						resultSet.last();
						size=resultSet.getRow();
						ticker=new HistoricalData[size];
						resultSet.beforeFirst();
					}
					while(resultSet.next())
					{
						HistoricalData data = new HistoricalData(resultSet.getString(1),resultSet.getDouble(2),resultSet.getDouble(3),
							resultSet.getDouble(4),resultSet.getDouble(5),resultSet.getLong(6),
							resultSet.getDate(7),resultSet.getInt(8));
							ticker[j]=data;
					       j++;
					}
				return ticker;
			}
		});
	}
		catch(EmptyResultDataAccessException e)
		{
			return null;
		}
	}
}
